package com.zmc.order.infrastructure.updater.order;

import com.zmc.common.domain.resp.order.RefundResp;
import com.zmc.common.domain.vo.third.PayRefundVo;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.common.utils.JsonUtils;
import com.zmc.order.feign.ThirdFeignService;
import com.zmc.order.infrastructure.entity.OrderEntity;
import com.zmc.order.infrastructure.entity.OrderReturnApplyEntity;
import com.zmc.order.infrastructure.enums.OrderEnum;
import com.zmc.order.infrastructure.service.MerchantOrderService;
import com.zmc.order.infrastructure.service.OrderReturnApplyService;
import com.zmc.order.infrastructure.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author：zmc
 * @Date：2025/5/15 18:24
 * 订单退款处理
 */
@Component
public class OrderRefundHandlerUpdater<T> implements OderUpdater<T> {

    public static Logger log = LoggerFactory.getLogger(OrderRefundApproveUpdater.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private OrderReturnApplyService orderReturnApplyService;

    @Autowired
    private ThirdFeignService thirdFeignService;

    @Override
    @Transactional
    public void execute(T param) {
        String orderSn = (String) param;
        OrderEntity order = orderService.getByOrderSn(orderSn);
        if (order == null) {
            log.error("当前订单不存在, orderSn:{}", orderSn);
            throw new BusinessException("当前订单不存在");
        }
        if (order.getStatus() == OrderEnum.ORDER_STATUS_REFUNDING.getCode()) {
            PayRefundVo vo = new PayRefundVo();
            vo.setOrderSn(order.getOrderSn());
            vo.setAmount(order.getPayAmount());
            vo.setRefundWay(order.getPayType());
            OrderReturnApplyEntity returnApplyEntity = orderReturnApplyService.getByOrderSn(orderSn);
            vo.setRefundReason(returnApplyEntity.getReason());
            RefundResp resp = JsonUtils.transToClass(thirdFeignService.refund(vo), RefundResp.class);
            //退款成功
            if (resp.isSuccess()) {
                //更新用户订单
                orderService.updateStatus(orderSn, OrderEnum.ORDER_STATUS_REFUNDED.getCode());
                //更新商户订单
                merchantOrderService.updateStatus(order.getMerchantOrderSn(), OrderEnum.ORDER_STATUS_REFUNDED.getCode());
            } else {
                log.error("支付宝退款异常， orderSn:{},status:{}", orderSn, order.getStatus());
            }
        } else {
            log.error("当前订单状态不能退款,请先申请， orderSn:{},status:{}", orderSn, order.getStatus());
            throw new BusinessException("当前订单状态不能退款");
        }
    }
}
